package com.southwind.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@RestController
@Slf4j
public class ConsumerController {


    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;


    @GetMapping("/instances")
    public List<ServiceInstance> instances() {
        List<ServiceInstance> provider = discoveryClient.getInstances("provider");
        return provider;
    }


//    @GetMapping("/index")
//    public String index() {
//        //调用 provider服务的index方法
//        //1.找到provider实例
//        List<ServiceInstance> provider = discoveryClient.getInstances("provider");
//        int i = ThreadLocalRandom.current().nextInt(provider.size());
//        ServiceInstance serviceInstance = provider.get(i);
//        String s = serviceInstance.getUri().toString() + "/index";
//        //2.调用
//        log.info("调用的端口是[{}]", serviceInstance.getPort());
//        String forObject = restTemplate.getForObject(s, String.class);
//        return "调用了端口为" + serviceInstance.getPort() + "返回结果是" + forObject;
//    }

    @GetMapping("/index")
    public String index() {
        return restTemplate.getForObject("http://provider/index", String.class);
    }
}
